/*

    ASFTagApp, edit tags in ASF files
    Copyright (C) 2010  Stefano Guidoni <ilguido@users.sf.net>

    ASFTagApp is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

import java.awt.*;
import java.awt.event.*;
import java.awt.Image;
import javax.swing.*;
import javax.swing.ImageIcon;
import java.net.URL;
import java.io.File;
import java.util.Locale;
import java.util.ResourceBundle;

// Main Class
// initialization and gui
public class ASFTagApp extends JPanel implements ActionListener,
                                      ItemListener { 
  
  public ASFTagApp() {
    JButton b;
    JPanel p, pp;
    JLabel l;
    Dimension dld = new Dimension(80, 24);

    Locale locallocale = Locale.getDefault();
    if (locallocale.getLanguage().equals("fr")) {
      Locale frlocale = new Locale("fr");
      rb = ResourceBundle.getBundle("ATAResources", frlocale);
    } else if (locallocale.getLanguage().equals("it")) {
      Locale itlocale = new Locale("it");
      rb = ResourceBundle.getBundle("ATAResources", itlocale);
    } else {
      Locale nulllocale = new Locale("");
      rb = ResourceBundle.getBundle("ATAResources", nulllocale);
    }

    filename = rb.getString("NOFILE");
    lf = new JLabel(rb.getString("FILE") + filename);
    lf.setEnabled(false);
    f = new JFrame("ASF Tag Editor");
    f.setLayout(new BorderLayout());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(false);

    URL urlIcon = getClass().getResource("asftagicon.png");
    Image icon = Toolkit.getDefaultToolkit().getImage(urlIcon);
    f.setIconImage(icon);

    URL urlLock = getClass().getResource("lock.png");
    URL urlUnlock = getClass().getResource("unlock.png");
    ImageIcon licon = new ImageIcon(urlLock);
    ImageIcon uicon = new ImageIcon(urlUnlock);

    f.add(p = new JPanel(), BorderLayout.PAGE_START);
    p.setPreferredSize(new Dimension(80, 54));
    p.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.black));
    p.add(lf, BorderLayout.CENTER);
    lf.setPreferredSize(new Dimension(360, 18));
    URL urlImg = getClass().getResource("refresh.png");
    ImageIcon img = new ImageIcon(urlImg);
    p.add(b = new JButton(rb.getString("REFRESH"), img), 
                  BorderLayout.LINE_START);
    b.setPreferredSize(new Dimension(112, 25));
    b.setActionCommand("Ricarica");
    b.setMnemonic(KeyStroke.getKeyStroke(rb.getString("REFRESH_M")).getKeyCode());
    b.addActionListener(this);
    urlImg = getClass().getResource("open.png");
    img = new ImageIcon(urlImg);
    p.add(b = new JButton(rb.getString("OPEN"), img), 
                  BorderLayout.PAGE_END);
    b.setPreferredSize(new Dimension(112, 25));
    b.setActionCommand("Apertura");
    b.setMnemonic(KeyStroke.getKeyStroke(rb.getString("OPEN_M")).getKeyCode());
    b.addActionListener(this);

    f.add(pp = new JPanel(), BorderLayout.CENTER);
    pp.setLayout(new GridLayout(6,1));

    pp.add(p = new JPanel());
    p.add(l = new JLabel(rb.getString("TITLE")), 
                 BorderLayout.WEST);
    l.setPreferredSize(dld);
    p.add(tft = new JTextField(24), 
                 BorderLayout.CENTER);
    tft.setPreferredSize(dld);
    p.add(ct = new JCheckBox(uicon),
                 BorderLayout.EAST);
    ct.setSelectedIcon(licon);
    ct.addItemListener(this);

    pp.add(p = new JPanel());
    p.add(l = new JLabel(rb.getString("AUTHOR")), 
                 BorderLayout.WEST);
    l.setPreferredSize(dld);
    p.add(tfa = new JTextField(24), 
                 BorderLayout.CENTER);
    tfa.setPreferredSize(dld);
    p.add(ca = new JCheckBox(uicon),
                 BorderLayout.EAST);
    ca.setSelectedIcon(licon);
    ca.addItemListener(this);

    pp.add(p = new JPanel());
    p.add(l = new JLabel(rb.getString("COPYRIGHT")), 
                 BorderLayout.WEST);
    l.setPreferredSize(dld);
    p.add(tfc = new JTextField(24), 
                 BorderLayout.CENTER);
    tfc.setPreferredSize(dld);
    p.add(cc = new JCheckBox(uicon),
                 BorderLayout.EAST);
    cc.setSelectedIcon(licon);
    cc.addItemListener(this);

    pp.add(p = new JPanel());
    p.add(l = new JLabel(rb.getString("DESCRIPTION")), 
                 BorderLayout.WEST);
    l.setPreferredSize(dld);
    p.add(tfd = new JTextField(24), 
                 BorderLayout.CENTER);
    tfd.setPreferredSize(dld);
    p.add(cd = new JCheckBox(uicon),
                 BorderLayout.EAST);
    cd.setSelectedIcon(licon);
    cd.addItemListener(this);

    pp.add(p = new JPanel());
    p.add(l = new JLabel(rb.getString("RATING")), 
                 BorderLayout.WEST);
    l.setPreferredSize(dld);
    p.add(tfv = new JTextField(24), 
                 BorderLayout.CENTER);
    tfv.setPreferredSize(dld);
    p.add(cv = new JCheckBox(uicon),
                 BorderLayout.EAST);
    cv.setSelectedIcon(licon);
    cv.addItemListener(this);

    pp.add(p = new JPanel());
    urlImg = getClass().getResource("clean.png");
    img = new ImageIcon(urlImg);
    p.add(bc = new JButton(rb.getString("CLEAN"), img), 
                  BorderLayout.WEST); 
    bc.setActionCommand("Pulisci");
    bc.setMnemonic(KeyStroke.getKeyStroke(rb.getString("CLEAN_M")).getKeyCode()); 
    bc.addActionListener(this);
    bc.setEnabled(false);
    urlImg = getClass().getResource("save.png");
    img = new ImageIcon(urlImg);
    p.add(bs = new JButton(rb.getString("SAVE"), img), 
                  BorderLayout.CENTER); 
    bs.setActionCommand("Salva");
    bs.setMnemonic(KeyStroke.getKeyStroke(rb.getString("SAVE_M")).getKeyCode());
    bs.addActionListener(this);
    bs.setEnabled(false);
    urlImg = getClass().getResource("exit.png");
    img = new ImageIcon(urlImg);
    p.add(be = new JButton(rb.getString("EXIT"), img), 
                  BorderLayout.EAST); 
    be.setActionCommand("Esci");
    be.setMnemonic(KeyStroke.getKeyStroke(rb.getString("EXIT_M")).getKeyCode()); 
    be.addActionListener(this); 

    f.add(sb = new JLabel(), BorderLayout.PAGE_END);
    sb.setPreferredSize(new Dimension(360,18));
    sb.setBorder(BorderFactory.createEtchedBorder());

    f.pack(); 
    f.setVisible(true); 
  }

  public static void main (String[] args) {
    try {
      //if (System.getProperty("os.name").compareTo("Linux") == 0) {
      //  UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
      //} else {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      //}
    }
    catch (UnsupportedLookAndFeelException e) {
      try {
       UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
      } 
      catch (Exception ex) {
        System.err.println("Err...");
      }
    }
    catch (Exception e) {
      System.err.println("Err...");
    }
    sem = true;
    new ASFTagApp();
  }

  private void OpenFile( ) {
    JFileChooser fd = new JFileChooser();
    fd.setDialogTitle(rb.getString("OPEN"));
    if (dir.length() > 3 ) {
      File tmp = new File(dir);
      fd.setCurrentDirectory(tmp);
    }
    int ret = fd.showOpenDialog(f);
    if (ret == JFileChooser.APPROVE_OPTION) {
      File tmp = fd.getSelectedFile();
      filename = tmp.getName();
      dir = tmp.getParent() + System.getProperty("file.separator");
    }
    if (filename.equals("null")) {
      filename = "";
      dir = "";
      lf.setText(rb.getString("FILE") + rb.getString("NOFILE"));
    } else {
      lf.setText(rb.getString("FILE") + filename);
    }
  }

  private void getAsfTags () {
    if (obf.tags_check(dir + filename)) {
      //System.out.println(rb.getString("ISASF"));
      sb.setText(rb.getString("ISASF"));
      lf.setEnabled(true);
      bc.setEnabled(true);
      bs.setEnabled(true);
    } else {
      //System.out.println(rb.getString("ISNOTASF"));
      sb.setText(rb.getString("ISNOTASF"));
      lf.setEnabled(false);
      bc.setEnabled(false);
      bs.setEnabled(false);
      filename = "";
      resetAsfTags();
      return;
    }  

    if (obf.tags_read(dir + filename)) {
      String str;
      if(ct.isSelected() == false) {
        str = new String(obf.lt, 0, (obf.tl-1)/2);
        tft.setText(str);
      }
      if(ca.isSelected() == false) {
        str = new String(obf.la, 0, (obf.al-1)/2);
        tfa.setText(str);
      }
      if(cc.isSelected() == false) {
        str = new String(obf.lc, 0, (obf.cl-1)/2);
        tfc.setText(str);
      }
      if(cd.isSelected() == false) {
        str = new String(obf.ld, 0, (obf.dl-1)/2);
        tfd.setText(str);
      }
      if(cv.isSelected() == false) {
        str = new String(obf.lr, 0, (obf.rl-1)/2);
        tfv.setText(str);
      }
    } else {
      resetAsfTags();
      return;
    }
    
  }
  
  private void resetAsfTags () {
    if(ct.isSelected() == false)
      tft.setText("");
    if(ca.isSelected() == false)
      tfa.setText("");
    if(cc.isSelected() == false)
      tfc.setText("");
    if(cd.isSelected() == false)
      tfd.setText("");
    if(cv.isSelected() == false)
      tfv.setText("");
  }

  private class WriteFile implements Runnable {
    public void run() {
      String ldir = dir;
      String lfilename = filename;
      if (obf.tags_write(ldir + lfilename, tft.getText(), tfa.getText(), tfc.getText(), tfd.getText(), tfv.getText())) {
        File f1, f2;
        f1 = new File(ldir + lfilename);
        f2 = new File(ldir + lfilename + ".tmp");
        if (f1.exists() && !f1.isDirectory()) {
          f1.delete();
          f2.renameTo(f1);
        }
      } else {
        File f2;
        f2 = new File(ldir + lfilename + ".tmp");
        f2.delete();
      }
      sb.setText(rb.getString("ISASF"));
      be.setEnabled(true);
    }
  }

  public void actionPerformed(ActionEvent e) {
    String s = e.getActionCommand();

    if (s.equals("Esci")) { 
      System.exit(0); 
    } else if (s.equals("Apertura")) { 
      OpenFile();
      getAsfTags();
    } else if (s.equals("Salva")) {
      if (sem == true) {
        sem = false;
        be.setEnabled(false);
        sb.setText(rb.getString("WAIT"));
        (new Thread(new WriteFile())).start();
        sem = true;
      }
    } else if (s.equals("Pulisci")) {
      obf.tags_reset();
      resetAsfTags();
    } else if (s.equals("Ricarica")) {
      getAsfTags();
    }
  }

  public void itemStateChanged(ItemEvent e) {
    Object source = e.getItemSelectable();
    
    if (source == ct) {
      tft.setEnabled(!(ct.isSelected()));
    } else if (source == ca) {
      tfa.setEnabled(!(ca.isSelected()));
    } else if (source == cc) {
      tfc.setEnabled(!(cc.isSelected()));
    } else if (source == cd) {
      tfd.setEnabled(!(cd.isSelected()));
    } else if (source == cv) {
      tfv.setEnabled(!(cv.isSelected()));
    }
  }


  public ASFTags obf = new ASFTags();

  private JFrame f; 
  private JButton bc;
  private JButton bs;
  private JButton be;
  private JLabel lf;
  private JLabel sb;
  private String filename;
  private String dir = "";
  private JTextField tft;
  private JTextField tfa;
  private JTextField tfc;
  private JTextField tfd;
  private JTextField tfv;
  private JCheckBox ct;
  private JCheckBox ca;
  private JCheckBox cc;
  private JCheckBox cd;
  private JCheckBox cv;

  private ResourceBundle rb;

  private static Boolean sem;

  private static final long serialVersionUID = 1899L;
} 
